package cn.bdqn.commen;

import cn.bdqn.entity.SysLog;
import cn.bdqn.entity.SysUser;
import cn.bdqn.service.sys.SysJournalService;
import cn.bdqn.utils.IpUtiles;
import cn.bdqn.utils.MyLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @ProjectName: ycbdqn
 * @Package: cn.bdqn.commen 系统日志：切面处理类 切面只记录除登陆和退出的记录 登录退出日志在监听器中记录
 * @Author: huat
 * @Date: 2020/3/5 22:26
 * @Version: 1.0
 */
@Aspect
@Component
public class SysLogAspect {
    @Autowired
    private SysJournalService sysLogService;

    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation( cn.bdqn.utils.MyLog)")
    public void logPoinCut() {
    }

    //切面 配置通知
    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) {

        //保存日志
        SysLog sysLog = new SysLog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取操作
        MyLog myLog = method.getAnnotation(MyLog.class);
        if (null!=myLog) {
            String value = myLog.value();
            sysLog.setOperation(value);//保存获取的操作
        }

        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        sysLog.setMethod(className + "." + methodName);

        sysLog.setCreateDate(new Date());
        //获取请求
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        //获取用户名
        SysUser sysUser=(SysUser) request.getSession().getAttribute("user");
        sysLog.setUsername(sysUser.getUsername());
        //获取用户ip地址
        sysLog.setIp(IpUtiles.getRealIp(request));
        //调用service保存SysLog实体类到数据库
        sysLogService.saveSysLog(sysLog);
    }

}
